var express = require('express');
let multer = require('multer');
let fs = require("fs");
let path = require("path");
var router = express.Router();
var model = require('../model/user')
const JWT = require('../controller/JWT')
router.post('/login', function (req, res, next) {
    model.doQuery(req.body.username, function succ(results) {
        console.log('results', results);
        if(results.length) {
            results = results[0]
            if(req.body.password === results.password) {
                res.send({
                    status: 200,
                    data: {
                        token: JWT.generate({
                            username: req.body.username,
                            password: results.password
                        })
                    },
                    msg:'登录成功！'
                })
            }
            else {
                res.send({
                    status: 401,
                    msg:'账号或密码错误！'
                })
            }
        }
        else {
            res.send({
                status: 401,
                msg:'请先注册！'
            })
        }
    }, function fail(err) {
        res.send({
            status: 200,
            data:err
        })
    })
});
router.post('/registary', function (req, res, next) {
    const doInsert = () => model.doInsert(req.body, function succ(results) {
        res.send({
            status: 200,
            data: results
        })
    }, function fail(err) {
        res.send({
            status: 200,
            data: err
        })
    })
    model.doQuery(req.body.username, function succ(results) {
        console.log('results', results);
        if(results.length == 0) {
            return doInsert();
        }
        res.send({
            status: 200,
            data:null,
            msg: '用户名重复'
        })
    }, function fail(err) {
        console.log('err', err);
        res.send({
            status: 200,
            data:err
        })
    })
});

module.exports = router;


